package com.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.dao.CheckGroupDao;
import com.entity.PageResult;
import com.entity.QueryPageBean;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pojo.CheckGroup;
import com.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

//检查组管理

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupDao checkGroupDao;
    @Override //新增检查组
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        //新增检查组
        checkGroupDao.add(checkGroup);
        //设置检查组与检查项的多对多的关系
        Integer checkGroupId = checkGroup.getId();
       this.setCheckGroupAndCheckItem(checkGroupId,checkitemIds);
    }

    @Override  //分页查询
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<CheckGroup> page = checkGroupDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override   //根据id查询id查询检查组
    public CheckGroup findById(Integer id) {
        return checkGroupDao.findById(id);
    }

    @Override   //根据检查组id查询检查组包含的检查项的id
    public List<Integer> findCheckItemsByCheckGroupId(Integer id) {
        return checkGroupDao.findCheckItemsByCheckGroupId(id);
    }

    @Override   //根据id修改检查组和检查组与检查项的多对多的关系
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        //1.根据id修改t_checkgroup表中的数据
        checkGroupDao.edit(checkGroup);
        //2.删除t_checkgroup_checkitem表中有关id的数据
        checkGroupDao.deleteAssociation(checkGroup.getId());
        //3.重新增加检查组与检查项的多对多关系
        Integer checkGroupId = checkGroup.getId();
        this.setCheckGroupAndCheckItem(checkGroupId,checkitemIds);
    }

    @Override    //查询所有检查组信息
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }

    public void setCheckGroupAndCheckItem(Integer checkGroupId,Integer[] checkitemIds){
        if (checkitemIds !=null && checkitemIds.length>0 ){
            for (Integer checkitemId : checkitemIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("checkGroupId",checkGroupId);
                map.put("checkitemId",checkitemId);
                checkGroupDao.setCheckGroupAndCheckItem(map);
            }
        }
    }
}
